import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getProposalList } from '@/api/proposal.js'
import { useAdminStore } from '@/stores/admin.js'
import { getDepartmentNameById } from '@/api/admin.js' // 导入新接口

export const useProposalStore = defineStore('proposal', () => {
  // 状态
  const tableData = ref([])
  const total = ref(0)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const dateRange = ref([])
  const sortBy = ref('desc')
  const status = ref('')
  const proposalType = ref('')
  const pageStatus = ref(0)
  const searchText = ref('') // 添加搜索文本状态

  const adminStore = useAdminStore()

  // 格式化日期
  const formatDate = (date) => {
    if (!date) return null
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  // 获取提案数据
  const fetchProposalData = async () => {
    // console.log("当前管理员的信息是：",adminStore.adminInfo)
    let departmentName = null;
    if (adminStore.adminInfo && adminStore.adminInfo.propositionsDepId) {
      try {
        const response = await getDepartmentNameById(adminStore.adminInfo.propositionsDepId);
        departmentName = response.data;
        console.log("当前管理员所属的提案部门名称是：", departmentName);
      } catch (error) {
        console.error('获取部门名称失败：', error);
      }
    }

    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      status: status.value && status.value !== 'all' ? status.value : null,
      proposalType: proposalType.value && proposalType.value !== 'all' ? proposalType.value : null,
      startDate: dateRange.value[0] ? formatDate(dateRange.value[0]) : null,
      endDate: dateRange.value[1] ? formatDate(dateRange.value[1]) : null,
      sort: sortBy.value || 'desc',
      department: departmentName,
      pageStatus: pageStatus.value,
      searchText: searchText.value // 添加搜索文本参数
    }
    console.log('现在是流程：', pageStatus.value)
    try {
      let result = await getProposalList(params)
      if (result && result.data) {
        tableData.value = result.data.items || []
        total.value = result.data.total || 0
      }
    } catch (error) {
      console.error('获取提案数据失败：', error)
    }
  }



  return {
    tableData,
    total,
    pageNum,
    pageSize,
    dateRange,
    sortBy,
    status,
    proposalType,
    pageStatus,
    searchText, // 导出搜索文本
    fetchProposalData
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'proposal-store',
        storage: localStorage,
        paths: ['pageNum', 'pageSize', 'dateRange', 'sortBy', 'status', 'proposalType', 'searchText'] // 添加searchText到持久化
      }
    ]
  }
}) 